package leetcode;

import java.util.concurrent.Semaphore;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 设有3个线程，让这3个线程顺序交替打印abc 10 次
 * @date 2020/3/10 22:44
 */
public class Code1114_PrintABC1 {

    public static void main(String[] args) throws InterruptedException {
        Semaphore semaphore = new Semaphore(1);
        AtomicInteger count = new AtomicInteger(0);
        final String[] msg = {"a"};

        int maxcount = 30;
        new Thread(()->{
            while (count.get() < maxcount){
                if(msg[0].equals("a")){
                    try {
                        semaphore.acquire();
                        if(count.get() < maxcount){
                            System.out.print("a");
                            msg[0] = "b";
                            count.getAndIncrement();
                        }

                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }finally {
                        semaphore.release();
                    }

                }
            }
        },"0").start();

        new Thread(()->{
            while (count.get() < maxcount){
                if(msg[0].equals("b")){
                    try {
                        semaphore.acquire();
                        if(count.get() < maxcount){
                            System.out.print("b");
                            msg[0] = "c";
                            count.getAndIncrement();
                        }
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }finally {
                        semaphore.release();
                    }

                }
            }
        },"1").start();

        new Thread(()->{
            while (count.get() < maxcount){
                if(msg[0].equals("c")){
                    try {
                        semaphore.acquire();
                        if(count.get() < maxcount){
                            System.out.println("c"+count.get());
                            msg[0] = "a";
                            count.getAndIncrement();
                        }
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }finally {
                        semaphore.release();
                    }

                }
            }
        },"2").start();

    }



}
